package com.rogue.blog.model.po;

import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 86101 on 2018-10-18.
 */
@Getter
@Setter
public class PageBean<T> {

    private final static Logger logger = LoggerFactory.getLogger(PageBean.class);

    private List<T> pageData = new ArrayList<>(); // 当前页的数据
    private int firstPage = 1; // 首页
    private int prePage = 1; // 上一页
    private int nextPage = 1; // 下一页
    private int totalPage = 1; // 末页、总页数
    private int currentPage = 1; // 当前页
    private int totalCount = 0; // 总记录数
    private int pageSize = 10; // 每页显示的记录数

    public Integer getFirstPage() {
        return 1;
    }

    /**
     * 计算上一页
     *
     * @return
     */
    public int getPrePage() {
        return Math.max(currentPage - 1, 1);
    }

    /**
     * 计算下一页
     *
     * @return
     */
    public int getNextPage() {
        return Math.min(currentPage + 1, totalPage);
    }

    public int getTotalPage() {
        return pageSize == 0 ?
                1
                :
                (totalCount % pageSize == 0 ?
                        totalCount / pageSize
                        : totalCount / pageSize + 1);
    }

    public <E> PageBean toPageBean(Class<E> clazz) throws Exception {
        PageBean<E> pageBean = new PageBean<>();
        List<E> newResult = new ArrayList<>();
        for (T dto : pageData) {
            E vo = clazz.newInstance();
            BeanUtils.copyProperties(dto, vo);
            newResult.add(vo);
        }
        BeanUtils.copyProperties(this, pageBean);
        pageBean.setPageData(newResult);
        return pageBean;
    }
}
